package com.hotel.customersystem.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotel.config.jwt.JwtConfig;
import com.hotel.config.aliyun.PhoneCodeConfig;
import com.hotel.config.qiniu.QiniuYunConfig;
import com.hotel.customersystem.mapper.CustomerUserMapper;
import com.hotel.customersystem.pojo.CustomerUser;
import com.hotel.customersystem.pojo.LoginUserVo;
import com.hotel.customersystem.pojo.UserVo;
import com.hotel.customersystem.service.CustomerUserService;
import com.hotel.websocketsystem.mapper.CustomerServiceUserMapper;
import com.hotel.websocketsystem.pojo.CustomerServiceUser;
import com.hotel.websocketsystem.service.CustomerServiceUserService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Map;
import java.util.UUID;

/**
 * (CustomerUser)表服务实现类
 *
 * @author makejava
 * @since 2022-09-30 16:33:32
 */
@Slf4j
@Service("customerUserService")
public class CustomerUserServiceImpl extends ServiceImpl<CustomerUserMapper, CustomerUser> implements CustomerUserService {


    // 注入手机验证码配置文件
    @Resource
    private PhoneCodeConfig phoneCodeConfig;

    @Resource
    private CustomerUserMapper customerUserMapper;

    @Resource
    private CustomerServiceUserMapper customerServiceUserMapper;

    // 注入jwt配置文件
    @Resource
    private JwtConfig jwtConfig;

    // 注入七牛云配置
    @Resource
    private QiniuYunConfig qinniuConfig;


    /**
     * 上传头像
     * @param userAdmin
     * @param imgUrl
     * @return
     * @throws QiniuException
     */
    @Override
    public Boolean uploadHeadPortrait(String userAdmin,String imgUrl) throws QiniuException {
        Auth auth = Auth.create(qinniuConfig.getAccessKey(),qinniuConfig.getSecretKey()); // 创建认证对象
        String token = auth.uploadToken(qinniuConfig.getBucket()); // 上传到对应的空间，得到token令牌
        log.info("token:",token);
//        指定的大区  zone0 华东 zone1 华北   zone2华南
        Configuration cfg=new Configuration(Zone.zone0()); // 配置存储区域
//        需要上传的文件的地址
        String local = imgUrl;
        log.info("imgUrl:",imgUrl);
//        上传文件的名称
        String imgName = UUID.randomUUID().toString();
        log.info("imgName",imgName);
        File file=new File(local);
//        进行图片的上传
        UploadManager uploadManager=new UploadManager(cfg);
        Response response = uploadManager.put(file, imgName, token);// 文件，文件名，令牌
        System.out.println(response);
        // 传入到数据库
        Boolean flag = removeUserHeadPortrait(userAdmin, imgUrl);
        // 判断是否上传成功
//        return Objects.equals(response.error, "null");
        return flag;
    }

    /**
     * 账号、密码、手机号登录
     * @param user
     * @return
     */
    @Override
    public LoginUserVo login(UserVo user) {
        // 密码不能为空
        if (Strings.isEmpty(user.getUserPasssword())) {
            return null;
        }
        // 1.验证用户名、密码
        LambdaQueryWrapper<CustomerUser> lbq = new LambdaQueryWrapper<>();
        lbq.eq(CustomerUser::getStandby01,user.getUserAdmin()).eq(CustomerUser::getUserPasssword,user.getUserPasssword());
        // 查询用户
        CustomerUser customerUser = customerUserMapper.selectOne(lbq);
        if (customerUser != null) {
            // 2.创建token
            String token = jwtConfig.createToken(customerUser.getStandby01());
            // 封装返回参数
            LoginUserVo result = new LoginUserVo();
            result.setUserId(customerUser.getUserId());
            result.setUserAdmin(customerUser.getStandby01());
            result.setUserNickName(customerUser.getUserNickName());
            result.setUserPasssword(customerUser.getUserPasssword());
            result.setUserPhone(customerUser.getUserPhone());
            //用户头像
            result.setUserPhoto(customerUser.getStandby02());
            result.setToken(token);
            System.out.println(result.toString());
            return result;
        } else return null;
    }

    /**
     * 根据验证码与手机号登录
     * @param phone
     * @param code
     * @return
     */
    @Override
    public LoginUserVo loginByPhoneCode(String phone, String code) {

        // 根据phone查询用户信息
        LambdaQueryWrapper<CustomerUser> lbq = new LambdaQueryWrapper<>();
        lbq.eq(CustomerUser::getUserPhone,phone); // 根据手机号查询用户信息
        CustomerUser customerUser = customerUserMapper.selectOne(lbq);
        // 封装用户信息
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserId(customerUser.getUserId());
        loginUserVo.setUserAdmin(customerUser.getStandby01());
        loginUserVo.setUserNickName(customerUser.getUserNickName());
        loginUserVo.setUserPhone(customerUser.getUserPhone());
        // 创建token
        loginUserVo.setToken(jwtConfig.createToken(loginUserVo.getUserAdmin()));
        return loginUserVo;
    }


    /**
     * 注册用户
     * @param customerUser
     * @return
     */
    @Override
    public Boolean register(CustomerUser customerUser) {
        // 会有问题  前端传的是useradmin  后端接受的是standby01
        int row = customerUserMapper.insert(customerUser);
//        CustomerUser user = new CustomerUser();
//        user.setStandby01(customerUser.getStandby01());
//        user.setUserNickName(customerUser.getUserNickName());
//        user.setStandby01(customerUser.getStandby01());
//        user.set(2); // 用户
//        int i = customerServiceUserMapper.insert(user);
//        return (row > 0 && i > 0);
        return null;
    }

    /**
     * 根据用户账号查询用户
     * @param userAdmin
     * @return
     */
    @Override
    public CustomerUser selectByAdmin(String userAdmin) {
        LambdaQueryWrapper<CustomerUser> lbq = new LambdaQueryWrapper<>();
        lbq.eq(CustomerUser::getStandby01,userAdmin);
        CustomerUser customerUser = customerUserMapper.selectOne(lbq);
        return customerUser;
    }

    /**
     * 发送成功验证码
     * @param map
     * @param phone
     * @return
     */
    @Override
    public Boolean sendPhoneCode(Map<String, Object> map, String phone) {
        if (Strings.isEmpty(phone)) return false; // 手机号不为空
        // 设置配置文件                                                                   密钥id                       密钥
        DefaultProfile profile = DefaultProfile.getProfile("default",phoneCodeConfig.getAccessKey(),phoneCodeConfig.getSecret());
        // 创建一个阿里云授权的终端
        IAcsClient client = new DefaultAcsClient(profile);
        // 创建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST); // post方法
        request.setSysDomain(phoneCodeConfig.getDomain());
        request.setSysVersion(phoneCodeConfig.getApiversion()); // API版本号
        request.setSysAction(phoneCodeConfig.getAction());
        request.putQueryParameter("PhoneNumbers",phone); // 手机号
        request.putQueryParameter("SignName",phoneCodeConfig.getSignName()); // 签名名称
        request.putQueryParameter("TemplateCode",phoneCodeConfig.getTemplateCode()); // 短信模板
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); // 验证码转成json数据
        try {
            // 得到返回值
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            System.out.println(response.getHttpResponse());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 替换用户库中的头像链接
     * @param userAdmin
     * @param imgURL
     * @return
     */
    public Boolean removeUserHeadPortrait(String userAdmin,String imgURL) {
        LambdaQueryWrapper<CustomerUser> lbq = new LambdaQueryWrapper<>();
        lbq.eq(CustomerUser::getStandby01,userAdmin);
        CustomerUser customerUser = customerUserMapper.selectOne(lbq);
        customerUser.setStandby02(imgURL); // 设置头像路径
        int row = customerUserMapper.update(customerUser, lbq);
        return row > 0;
    }

}

